﻿using System;
using System.Collections.ObjectModel;
using System.Composition;
using System.Windows.Input;
using Unread.App.Common;
using Unread.App.Services.Interfaces;
using Unread.App.Views;
using Unread.Business.Models;

namespace Unread.App.ViewModels
{
    [Export]
    public class UnreadFeedViewModel : BindableBase
    {
        private readonly INavigationService _navigationService;

        private Guid _feedId;
        public Guid FeedId 
        { 
            get { return _feedId; } 
            set { SetProperty(ref _feedId, value); } 
        }

        private string _title;
        public string Title 
        {
            get { return _title; }
            set { SetProperty(ref _title, value); } 
        }

        private FeedItem _selectedFeedItem;
        public FeedItem SelectedFeedItem
        {
            get { return _selectedFeedItem; }
            set { SetProperty(ref _selectedFeedItem, value); }
        }

        public ObservableCollection<UnreadFeedItemViewModel> UnreadItems { get; set; }

        public UnreadFeedViewModel(INavigationService navigationService)
        {
            if (navigationService == null) throw new ArgumentNullException("navigationService");

            _navigationService = navigationService;

            UnreadItems = new ObservableCollection<UnreadFeedItemViewModel>();

            OpenFeedCommand = new DelegateCommand(OpenFeed, CanOpenFeed);

            PropertyChanged += UnreadViewModel_PropertyChanged;
        }

        private void UnreadViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "SelectedFeedItem")
                if (CanOpenFeedItem(_selectedFeedItem))
                    OpenFeedItem(_selectedFeedItem);
        }

        #region OpenFeedCommand

        public ICommand OpenFeedCommand { get; set; }

        private bool CanOpenFeed(object arg)
        {
            return true;
        }

        private void OpenFeed(object obj)
        {
            var feed = (obj as UnreadFeedViewModel);
            var navArgs = new FeedItemIdentifier { FeedId = FeedId, FeedItemUri = null };

            _navigationService.Navigate(typeof(FeedItemPage), navArgs);
        }

        #endregion

        #region OpenFeedItemCommand

        private bool CanOpenFeedItem(object arg)
        {
            return (arg as FeedItem != null);
        }

        private void OpenFeedItem(object obj)
        {
            var feedItem = (obj as FeedItem);
            var navArgs = new FeedItemIdentifier { FeedId = FeedId, FeedItemUri = feedItem.Link };

            _navigationService.Navigate(typeof(FeedItemPage), navArgs);
        }

        #endregion
    }
}